from django.http import HttpResponse
from django.template.context import Context, RequestContext
from mako.lookup import TemplateLookup
from mysite import settings
import logging

logger = logging.getLogger(__name__)

MYLOOKUP = TemplateLookup(directories=settings.MAKO_TEMPLATE_DIR,
                          module_directory=settings.MAKO_TEMPLATE_MODULE_DIR,
                          output_encoding='utf-8',
                          input_encoding='utf-8',
                          encoding_errors='replace',
                          collection_size=500,
                          )

def render_mako(template_name, dictionary={}, context_instance=None):
    logger.error('render_mako----in----')
    logger.error('MAKO_TEMPLATE_DIR:' + settings.MAKO_TEMPLATE_DIR)
    logger.error('MAKO_TEMPLATE_MODULE_DIR:' + settings.MAKO_TEMPLATE_MODULE_DIR)
    mako_temp = MYLOOKUP.get_template(template_name)
    if context_instance:
        context_instance.update(dictionary)
    else:
        context_instance = Context(dictionary)
    data = {}
    for d_instance in context_instance:
        data.update(d_instance)
    logger.error('render_mako----out----')
    return HttpResponse(mako_temp.render_unicode(**data))


def render_mako_context(request, template_name, dictionary={}):
    context_instance = RequestContext(request)
    return render_mako(template_name,
                       dictionary=dictionary,
                       context_instance=context_instance)


def render_mako_tostring(template_name, dictionary={}, context_instance=None):
    mako_temp = MYLOOKUP.get_template(template_name)
    if context_instance:
        context_instance.update(dictionary)
    else:
        context_instance = Context(dictionary)
    data = {}
    for d_instance in context_instance:
        data.update(d_instance)
    return mako_temp.render_unicode(**data)


def render_mako_tostring_context(request, template_name, dictionary={}):
    context_instance = RequestContext(request)
    return render_mako_tostring(template_name,
                                dictionary=dictionary,
                                context_instance=context_instance)
